package service

import (
	"context"
	"errors"
	"pmservice/db"
	"pmservice/graph/model"
)

// HospitalNew is the resolver for the HospitalNew field.
func (s *Service) HospitalNew(ctx context.Context, input model.HosNew) (*model.Hospital, error) {
	h, err := db.HospitalNew(s.Orm.DB, &input)
	if err != nil {
		return nil, err
	}
	return s.HospitalGetCompositeData(ctx, h, "")
}

// HospitalSave is the resolver for the HospitalSave field.
func (s *Service) HospitalSave(ctx context.Context, uid string, input model.HosEdit) (bool, error) {
	return db.HospitalSave(s.Orm.DB, uid, &input), nil
}

func (s *Service) HospitalGetCompositeData(ctx context.Context, d *db.Hospital, prefix string) (*model.Hospital, error) {
	ret := d.ToGQL()
	if HasField(ctx, PrefixJoin(prefix, "facs")) {
		facs, _ := s.FacSearch(ctx, model.FacSearchCond{
			Hosuid: d.UID,
		}, PrefixJoin(prefix, "facs"))
		if facs != nil {
			ret.Facs = facs.Results
		}
	}

	if HasField(ctx, PrefixJoin(prefix, "doctors")) {
		doctors, _ := s.DoctorSearch(ctx, model.DoctorSearchCond{
			Hosuid: d.UID,
		}, PrefixJoin(prefix, "doctors"))
		if doctors != nil {
			ret.Doctors = doctors.Results
		}
	}

	return ret, nil
}

// HospitalGet is the resolver for the HospitalGet field.
func (s *Service) HospitalGet(ctx context.Context, uid string, prefix string) (*model.Hospital, error) {
	h := db.HospitalGet(s.Orm.DB, uid)
	if h == nil {
		return nil, errors.New("hospital not found")
	}

	return s.HospitalGetCompositeData(ctx, h, prefix)
}
